$(function () {

    layui.config({
        base: '/Public/'
    }).extend({
        formSelects: 'layui-formSelects/src/formSelects-v4'
    });

    layui.use(['layer','form','element','formSelects','upload'], function () {

        var layer = layui.layer,
            form = layui.form,
            element = layui.element,
            upload = layui.upload,
            formSelects = layui.formSelects;

        var SUB_NAME,
            SUB_TYPE;

        //富文本编辑器
        var editor = new Simditor({
            textarea: $('#editor'),
            toolbar: [
                'bold',
                'italic',
                'underline',
                'strikethrough',
                'color',
                'emoji',
                '|',
                'ol',
                'ul',
                'blockquote',
                'code',
                'link',
                'image',
                'hr',
                /*'indent',
                'outdent',*/
                'alignment'
            ],
            emoji: {
                imagePath: '/Public/simditor-emoji/images/emoji',
                images : [
                    /*'hbf2019_jinli_org.png',
                    '2018new_zhongguozan_org.png',*/
                    '2018new_erha_org.png',
                    /*'2018new_baobao_org.png',
                    '2018new_tanshou_org.png',
                    '2018new_gui_org.png',*/
                    '2018new_doge02_org.png',
                    '2018new_miaomiao_org.png',
                    '2018new_xiongmao_org.png',
                    '2018new_jiyan_org.png',
                    '2018new_xiaoku_thumb.png',
                    '2018new_qinqin_org.png',
                    '2018new_touxiao_org.png',
                    '2018new_kuxiao_org.png',
                    '2018new_xiaoerbuyu_org.png',
                    '2018new_haha_org.png',
                    '2018new_han_org.png',
                    '2018new_aini_org.png',
                    '2018new_chijing_org.png',
                    '2018new_dalian_org.png',
                    '2018new_chigua_org.png',
                    '2018new_chongjing_org.png',
                    '2018new_huaixiao_org.png',
                    '2018new_huaxin_org.png',
                    '2018new_yinxian_org.png',
                    '2018new_yun_org.png',
                    '2018new_zhouma_org.png',
                    '2018new_wenhao_org.png',
                    '2018new_wu_org.png',
                    '2018new_xixi_org.png',
                    '2018new_leimu_org.png',
                    '2018new_ku_org.png',
                    '2018new_kelian_org.png',
                    '2018new_beishang_org.png',
                    '2018new_chanzui_org.png',
                    '2018new_dahaqian_org.png',
                    '2018new_ningwen_org.png',
                    '2018new_nu_org.png',
                    '2018new_qian_org.png',
                    '2018new_shengbing_org.png',
                    '2018new_shuai_org.png',
                    '2018new_shuijiao_thumb.png',
                    '2018new_wabi_thumb.png',
                    '2018new_weiqu_org.png',
                    '2018new_zhuakuang_org.png',
                    '2018new_zuohengheng_org.png',
                    '2018new_youhengheng_org.png',
                    '2018new_heng_org.png',
                    '2018new_guzhang_org.png',
                    '2018new_heixian_org.png',
                    '2018new_tu_org.png',
                    '2018new_kouzhao_org.png',
                    '2018new_tianping_org.png',
                    '2018new_xianhua_org.png',
                ],
            },
            upload: {
                url: '/BBS/uploadImage',
                params: null,
                fileKey: 'file',
                connectionCount: 3,
                leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
            }
        });

        var attachmentData = new Array();	//定义存放附件的对象

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: '/BBS/upload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,gif,xlsx,docx,pdf'
            },
            method: 'POST',
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' +
                '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' +
                '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' +
                '<div class="clearfix"></div>' +
                '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {

            data.SUB_NAME = SUB_NAME;
            data.DIR = '/BBS/';

        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {	//文件了上传成功后触发

            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                var attachmentObject = new Object();
                attachmentObject.savename = response.savename;
                attachmentObject.ext = response.ext;
                attachmentObject.path = response.path;
                attachmentData.push(attachmentObject);
            } else {
                layer.closeAll();
                layer.msg(response.msg, {icon: 2, time: 2000});
            }
        });

        // 所有文件上传结束时
        uploader.on('uploadFinished', function () {
            $.ajax({
                url: '/BBS/insertAttachment',
                type: 'POST',
                data: {
                    SUB_NAME: SUB_NAME,
                    SUB_TYPE: SUB_TYPE,
                    attachments: JSON.stringify(attachmentData)
                },
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 1, time: 2000});
                        setTimeout(function () {
                            location.href = '/BBS/detail/id/' + SUB_NAME;
                        }, 2000);
                    } else {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 2, time: 2000});
                    }
                }
            });
        });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, {icon: 2, time: 2000});
        });

        $('.uploader-file-queue').on('click', '.icon-remove', function () {

            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            uploader.removeFile( id, true );
            // 删除dom节点
            $(this).parent().parent().remove();

        });


        /**
         * 投票
         */
        var voteData = {};

        form.on('radio(choice)',function (data) {
            var dataChoice = data.value;
            //若为多选需设定最多选择项数
            if (dataChoice === '多选') {
                $('.layui-input-num').show();
                $(".layui-input-num").attr('name','num');
            } else {
                $('.layui-input-num').hide();
                $(".layui-input-num").removeAttr('name');
            }
        });

        //截止时间
        $('#date-end').datetimepicker({
            language: 'zh-CN',
            format: "yyyy-mm-dd hh:ii:ss",
            todayHighlight: true,
            autoclose: true,
            todayBtn: true
        });

        //投票选项的增加与删除
        function creatContent(number){
            var html = '<div class="layui-input-block">\n' +
                '                                <input type="text" class="layui-input layui-input-vote" name="vote-content' + number + '" placeholder="在此输入该选项内容..." lay-verify="required">\n' +
                '                                <button type="button" class="layui-btn layui-btn-primary" data-action="add" title="增加选项">\n' +
                '                                    <i class="icon-plus"></i>\n' +
                '                                </button>\n' +
                '                                <button type="button" class="layui-btn layui-btn-primary" data-action="cut" title="删除选项">\n' +
                '                                    <i class="icon-minus"></i>\n' +
                '                                </button>\n' +
                '                            </div>';
            return html;
        }

        var number = 2; //区分每个选项框的取值

        $('.vote-content').on('click', 'button',function(){
            if ($(this).attr('data-action') === 'add') {
                number++;
                $(this).parent().after(creatContent(number));
            }
            if ($(this).attr('data-action') === 'cut') {
                $(this).parent().remove();
            }

        });


        /**
         ***  基于element tree实现下拉框树的选择
         */
        var contentId;

        var tree = new Vue({
            el: '.tree',
            data() {
                return {
                    searchText: '',
                    /*data: {
                        api:{
                            treeDataList:"192.168.0.10/api.php/user/users",   // 得到节点数据，无层级结构 GET
                        }},*/
                    data: [{
                        id: 1,
                        label: '全公司',
                        children: [{
                            id: 11,
                            label: '研发部',
                            children: [{
                                id: 111,
                                label: 'AAA'
                            },{
                                id: 112,
                                label: 'BBB'
                            },{
                                id: 113,
                                label: 'CCC'
                            },]
                        },{
                            id: 12,
                            label: '人事行政部',
                            children: [{
                                id: 121,
                                label: 'aaaa'
                            },{
                                id: 122,
                                label: 'bbbb'
                            },{
                                id: 123,
                                label: 'cccc'
                            },]
                        },{
                            id: 13,
                            label: '财务部',
                            children: [{
                                id: 131,
                                label: 'a'
                            },{
                                id: 132,
                                label: 'b'
                            },{
                                id: 133,
                                label: 'c'
                            },]
                        }]
                    }],
                    defaultProps: {
                        children: 'children',
                        label: 'label'
                    }
                }
            },
            watch: {
                // 节点筛选
                searchText(val){
                    this.$refs.tree.filter(val);
                }
            },
            methods: {

                //对树节点进行筛选时执行的方法
                searchNode(value, data) {
                    if (!value) return true;
                    return data.label.indexOf(value) !== -1;
                },

                //复选框被点击时触发
                getCheckClick (e, node) {

                    var treeNode = []; //统计选中叶节点序号
                    var content=[];//显示所选内容
                    var k = 0;

                    contentId = this.$refs.tree.getCheckedKeys(true);  //获取选中的叶子节点id
                    console.log(contentId);

                    for (var i=0;i<node.checkedNodes.length;i++) { //循环选中的节点对象
                        //判断是否有孩子
                        if (node.checkedNodes[i].children != undefined) {
                            content[k] = node.checkedNodes[i].label; //如果有孩子就收集该节点的label
                            k++;
                            // console.log(node.checkedNodes[i].label)
                        }
                        treeNode[i] = node.checkedNodes[i].$treeNodeId;  //记录选中的节点在树中的序号
                    }

                    //判断是否是半选状态
                    if (node.halfCheckedKeys.length > 1) {
                        for (i=1;i<node.halfCheckedNodes.length;i++) {  //循环半选中的节点对象
                            for (var j=0;j<node.halfCheckedNodes[i].children.length;j++) {   //循环半选中的孩子节点
                                if ($.inArray(node.halfCheckedNodes[i].children[j].$treeNodeId,treeNode) >= 0) {  //通过该孩子节点在树中的序号是否在已选中的treeNode
                                    content[k] = node.halfCheckedNodes[i].children[j].label;    //如果在就收集该节点的label
                                    k++;
                                    // console.log(node.halfCheckedNodes[i].children[j].label)
                                }
                            }
                        }
                    }

                    //如果选取全公司就显示全公司
                    if ($.inArray('全公司',content) >= 0) {
                        $('.layui-tree-select .layui-input').val('全公司');
                    } else {
                        $('.layui-tree-select .layui-input').val(content.join('、'));
                    }
                }
            }
        }) ;

        /**
         ***  自定义下拉框样式同步layui
         */
        $('.layui-tree-select').click(function (e) {

            //点击下拉框出现与消失
            if($(".tree.layui-input-block").css("display")=="none"){
                $(".tree.layui-input-block").show();
            } else {
                $(".tree.layui-input-block").hide();
            }

            //剪头转向
            $('.layui-tree-select').toggleClass('layui-tree-selected');
            //激活搜索框
            $('.tree.layui-input-block .el-input .el-input__inner').focus();

            //点击空白处选择框也消失
            $(document).one("click", function(){
                $(".tree.layui-input-block").hide();
                $('.layui-tree-select').toggleClass('layui-tree-selected');
            });
            e.stopPropagation();
        });


        //展示模板
        $('.model').click(function () {
            $('.model').removeClass('active'); //移除其他的选中情况
            $(this).addClass('active'); //标注当前选中

            var dataModel = $(this).attr('data-model');//选取的模板号
            voteData = {'dataModel' : dataModel}
        });

        //进度条测试数据
        var percentData = ['2/8','5/8','1/8'];
        $(".vote-show").find(".layui-progress-bar").each(function (i) {
            $(this).attr("lay-percent", percentData[i]);
        });
        element.init();

        //layui上传文件
        upload.render({
            elem: '#upload' //绑定元素
            ,url: '/upload/' //上传接口
            ,done: function(res){
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });


        /**
         * 提交数据
         */
        form.on('submit(publish)',function (data) {
            voteData = $.extend(voteData, data.field); //合并对象
            voteData.userId = contentId;
           console.log(voteData);

            $.post('/Posts/post', voteData, function(response) {
                if (response.flag > 0) {
                    SUB_NAME = response.id;
                    SUB_TYPE = response.type;
                    if (uploader.getFiles().length > 0) {
                        uploader.upload();
                    } else {
                        location.href = '/BBS/detail/id/' + response.id;
                    }
                } else {
                    layer.close(loading);
                    layer.alert(response.msg);
                }
            }, 'json');
        });

    })
});